﻿using System;
using System.IO;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace MiniJavaScanner
{
    public partial class Form1 : Form
    {
        private Scanner scanner;
        private List<Token> idTokens;

        public Form1()
        {
            InitializeComponent();
            scanner = new Scanner();
            idTokens = new List<Token>();
        }

        private void ParseFile(string filePath)
        {
            this.Text = "Scanner - " + filePath;
            idTokens.Clear();
            rtbTokens.Clear();
            rtbIds.Clear();
            scanner.SetText(File.ReadAllText(filePath));

            Token t;
            do
            {
                t = scanner.GetNextToken();
                rtbTokens.Text += t.ToString() + "\n";
                if (t.Type == TokenType.ID)
                {
                    AddIdToken(t);
                }
            } while (t.Type != TokenType.EOF);
        }

        private void AddIdToken(Token t)
        {
            if (idTokens.IndexOf(t) >= 0)
            {
                return;
            }

            idTokens.Add(t);
            rtbIds.Text += t.ToString() + "\n";
        }
                
        private void openToolStripMenuItem_Click(object sender, EventArgs e)
        {
            OpenFileDialog ofd = new OpenFileDialog();
            ofd.InitialDirectory = getTestFilesFolderPath();
            ofd.Multiselect = false;
            ofd.CheckPathExists = true;
            ofd.CheckFileExists = true;
            ofd.AddExtension = true;
            ofd.Filter = "MiniJava files(.java)|*.java|Simple text files(.txt)|*.txt|All files|(*.*)";

            if (ofd.ShowDialog(this) == DialogResult.OK)
            {
                ParseFile(ofd.FileName);
            }
        }

        private string getTestFilesFolderPath()
        {
            return System.IO.Path.GetDirectoryName(Environment.GetCommandLineArgs()[0]) + @"\test";
        }
    }
}
